import { Breadcrumb, Button, Steps, Result, Space, Spin } from 'antd'
import styled from 'styled-components'
import { Link, useNavigate } from 'react-router-dom'
import { useState, useRef, useEffect } from 'react'
import { updateService, getServiceCatalogDetail } from '@/api/sharing/serviceCatalog'
import { useParams } from '@/router/hooks'
import BaseInfoForm from './modules/BaseInfoForm'
import ApiReQForm from './modules/ApiReQForm'
import BackEndServiceForm from './modules/BackEndServiceForm'

const steps = [
  {
    title: '基本信息',
  },
  {
    title: '定义API请求',
  },
  {
    title: '定义后端服务',
  },
  {
    title: '创建完成',
  },
]

const ServiceCatalogEdit = () => {
  const { id } = useParams()
  const [current, setCurrent] = useState(0)
  const [fullData, setFullData] = useState({})
  const [loading, setLoading] = useState(true)
  const formRefs = useRef([])
  const navigate = useNavigate()
  useEffect(() => {
    getServiceCatalogDetail(id)
      .then((response) => {
        const data = response.data
        data.labels = Object.values(data.labels)
        formRefs.current?.[0].setFieldsValue({ name: data.name, desc: data.desc, labels: data.labels })
        formRefs.current?.[1].setFieldsValue(data.apiRequestVo)
        formRefs.current?.[2].setFieldsValue(data.apiBacServiceVo)
        setFullData(data)
      })
      .finally(() => {
        setLoading(false)
      })
  }, [])
  const next = () => {
    setCurrent(current + 1)
  }
  const prev = () => {
    setCurrent(current - 1)
  }
  const items = steps.map((index, item) => ({
    key: item.index,
    title: item.title,
  }))
  const contentStyle = {
    // lineHeight: '260px',
    // textAlign: 'center',
    // color: token.colorTextTertiary,
    // backgroundColor: token.colorFillAlter,
    // borderRadius: token.borderRadiusLG,
    // border: `1px dashed ${token.colorBorder}`,
    // marginTop: 16,
  }
  /* 提交表单操作 */
  const handleSubmitForm = () => {
    Promise.all(
      formRefs.current.map((ref, index) => {
        return ref.validateFields().catch((e) => {
          return Promise.reject({ ...e, index })
        })
      })
    )
      .then(() => {
        const values = formRefs.current.map((ref) => ref.getFieldsValue())
        const formValues = { ...values[0], apiRequestDto: { ...values[1] }, apiServiceDto: { ...values[2] } }
        const options = formRefs.current?.[0]?.options || []
        /* 将选项转换为对象 */
        if (Array.isArray(formValues.labels)) {
          const optionsMap = new Map(options.map((option) => [option.value, option.label]))
          formValues.labels = formValues.labels.reduce((acc, item) => {
            if (optionsMap.has(item)) {
              acc[optionsMap.get(item)] = item
            }
            return acc
          }, {})
        }
        const formData = {
          apiRequestDto: formValues.apiRequestDto,
          apiServiceDto: formValues.apiServiceDto,
          name: formValues.name,
          desc: formValues.desc,
          labels: formValues.labels,
          createTime: fullData.createTime,
          id: fullData.id,
          uri: fullData.uri,
          status: fullData.status,
        }
        return updateService(formData)
      })
      .then((response) => {
        if (response.code === 200) {
          next()
        }
      })
      .catch((e) => {
        setCurrent(e.index)
      })
  }

  return (
    <StyleWrap>
      <Spin spinning={loading} tip="Loading...">
        <div className="page-breadcrumb">
          <Breadcrumb
            items={[
              {
                key: 'serviceCatalog', // 添加 key
                title: <Link to="/integration/sharing/serviceCatalog">服务目录</Link>,
              },
              {
                key: 'dataEdit', // 添加 key
                title: '数据编辑',
              },
            ]}
          />
        </div>
        <div className="steps-wrapper">
          <Steps current={current} items={steps} />
        </div>
        <div className="forms-wrapper">
          <BaseInfoForm
            style={{ display: current === 0 ? 'block' : 'none' }}
            ref={(el) => {
              if (el) formRefs.current[0] = el
            }}
          />
          <ApiReQForm
            style={{ display: current === 1 ? 'block' : 'none' }}
            ref={(el) => {
              if (el) formRefs.current[1] = el
            }}
          />
          <BackEndServiceForm
            style={{ display: current === 2 ? 'block' : 'none' }}
            ref={(el) => {
              if (el) formRefs.current[2] = el
            }}
          />
          <Result
            style={{ display: current === 3 ? 'block' : 'none' }}
            status="success"
            title="API服务修改完成!"
            extra={[
              <Button type="primary" key="console" onClick={() => navigate('/integration/sharing/serviceCatalog')}>
                返回服务目录
              </Button>,
            ]}
          />
        </div>
        <div className="buttons-wrapper">
          <Space
            size="large"
            style={{
              marginTop: 24,
              display: current === steps.length - 1 ? 'none' : undefined,
            }}
          >
            <Button disabled={current === 0 || current === steps.length - 1} onClick={() => prev()}>
              上一步
            </Button>
            <Button disabled={current >= steps.length - 2} onClick={() => next()}>
              下一步
            </Button>
            <Button type="primary" onClick={handleSubmitForm}>
              提交
            </Button>
          </Space>
        </div>
      </Spin>
    </StyleWrap>
  )
}

const StyleWrap = styled.div`
  padding: 16px;
  .steps-wrapper {
    width: 70%;
  }
  .forms-wrapper {
    margin-top: 30px;
  }
  .buttons-wrapper {
    /* width: 70%; */
    /* text-align: center; */
  }

  .ant-input,
  textarea.ant-input,
  .ant-select {
    max-width: 600px;
  }
  .ant-form-item-label {
    width: 120px;
    text-align: right;
  }
`
export default ServiceCatalogEdit
